/**
 * @param {number[]} nums
 * @return {number}
 * 输入：nums = [-2,1,-3,4,-1,2,1,-5,4]
输出：6
解释：连续子数组 [4,-1,2,1] 的和最大，为 6 。
 */
var maxSubArray = function (nums) {
  let left = 0
  let right = 0
  let curTotal = nums[0]
  let max = nums[0]
  while (right < nums.length - 1) {
    right++
    const currentTotal = curTotal + nums[right]
    if (nums[right] >= 0 && curTotal >= 0) {
      max = Math.max(max, currentTotal)
      curTotal = currentTotal
      continue
    }
    // 如果当前值大于上次的值
    let leftTem = left
    let temTotal = currentTotal
    let temMax = { currentTotal, index: leftTem }
    while (leftTem < right) {
      temTotal = temTotal - nums[leftTem]
      leftTem++
      if (temTotal >= temMax.currentTotal) {
        temMax.currentTotal = temTotal
        temMax.index = leftTem
      }
    }
    left = temMax.index
    max = Math.max(temMax.currentTotal, max)
    curTotal = temMax.currentTotal
  }
  return max
}
console.log(maxSubArray([-2, -1]))
